'use client';

import React, { useState } from 'react';
import { toast } from 'react-hot-toast';

interface TradingFormProps {
  currentPrice: number;
  symbol: string;
  onPriceFromOrderBook?: number;
}

export default function TradingForm({ 
  currentPrice, 
  symbol, 
  onPriceFromOrderBook 
}: TradingFormProps) {
  const [activeTab, setActiveTab] = useState<'buy' | 'sell'>('buy');
  const [orderType, setOrderType] = useState<'limit' | 'market'>('limit');
  const [price, setPrice] = useState(onPriceFromOrderBook || currentPrice);
  const [amount, setAmount] = useState('');
  const [isAdvanced, setIsAdvanced] = useState(false);
  const [loading, setLoading] = useState(false);

  // 高级选项状态
  const [stopLoss, setStopLoss] = useState('');
  const [takeProfit, setTakeProfit] = useState('');
  const [icebergVisible, setIcebergVisible] = useState('');

  // 模拟用户余额
  const [balances] = useState({
    USDT: 10000,
    BTC: 0.5
  });

  const baseCurrency = symbol.split('/')[0]; // BTC
  const quoteCurrency = symbol.split('/')[1]; // USDT

  const totalAmount = orderType === 'market' ? 
    parseFloat(amount || '0') * currentPrice : 
    parseFloat(amount || '0') * parseFloat(price.toString() || '0');

  // 百分比快捷选择
  const handlePercentageClick = (percentage: number) => {
    if (activeTab === 'buy') {
      const availableBalance = balances[quoteCurrency as keyof typeof balances];
      const maxAmount = orderType === 'market' ? 
        (availableBalance * percentage / 100) / currentPrice :
        (availableBalance * percentage / 100) / parseFloat(price.toString() || '0');
      setAmount(maxAmount.toFixed(6));
    } else {
      const availableBalance = balances[baseCurrency as keyof typeof balances];
      const maxAmount = availableBalance * percentage / 100;
      setAmount(maxAmount.toFixed(6));
    }
  };

  const handleSubmit = async () => {
    // 验证逻辑
    if (orderType === 'limit' && (!price || parseFloat(price.toString()) <= 0)) {
      toast.error('价格必须大于0');
      return;
    }
    
    if (!amount || parseFloat(amount) <= 0) {
      toast.error('数量必须大于0');
      return;
    }

    if (activeTab === 'buy') {
      const requiredBalance = totalAmount;
      if (requiredBalance > balances[quoteCurrency as keyof typeof balances]) {
        toast.error('余额不足');
        return;
      }
    } else {
      if (parseFloat(amount) > balances[baseCurrency as keyof typeof balances]) {
        toast.error('余额不足');
        return;
      }
    }

    setLoading(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      toast.success(`${activeTab === 'buy' ? '买入' : '卖出'}订单提交成功`);
      setAmount('');
    } catch {
      toast.error('订单提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 当从订单簿点击价格时更新
  React.useEffect(() => {
    if (onPriceFromOrderBook) {
      setPrice(onPriceFromOrderBook);
    }
  }, [onPriceFromOrderBook]);

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 h-full">
      {/* 买入/卖出选项卡 */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('buy')}
          className={`flex-1 px-4 py-3 text-sm font-medium ${
            activeTab === 'buy'
              ? 'text-green-600 dark:text-green-400 border-b-2 border-green-600 dark:border-green-400 bg-green-50 dark:bg-green-900/20'
              : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          买入 {baseCurrency}
        </button>
        <button
          onClick={() => setActiveTab('sell')}
          className={`flex-1 px-4 py-3 text-sm font-medium ${
            activeTab === 'sell'
              ? 'text-red-600 dark:text-red-400 border-b-2 border-red-600 dark:border-red-400 bg-red-50 dark:bg-red-900/20'
              : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          卖出 {baseCurrency}
        </button>
      </div>

      <div className="p-4 space-y-4">
        {/* 订单类型 */}
        <div className="flex space-x-2">
          <button
            onClick={() => setOrderType('limit')}
            className={`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${
              orderType === 'limit'
                ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            限价
          </button>
          <button
            onClick={() => setOrderType('market')}
            className={`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${
              orderType === 'market'
                ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            市价
          </button>
        </div>

        {/* 价格输入 */}
        {orderType === 'limit' && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              价格 ({quoteCurrency})
            </label>
            <input
              type="number"
              value={price}
              onChange={(e) => setPrice(parseFloat(e.target.value) || 0)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="输入价格"
              step="0.01"
            />
          </div>
        )}

        {orderType === 'market' && (
          <div className="p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md">
            <p className="text-sm text-yellow-800 dark:text-yellow-200">
              市价单将以当前最优价格成交: ${currentPrice.toLocaleString()}
            </p>
          </div>
        )}

        {/* 数量输入 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            数量 ({baseCurrency})
          </label>
          <input
            type="number"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="输入数量"
            step="0.000001"
          />
          
          {/* 百分比快捷选择 */}
          <div className="flex space-x-2 mt-2">
            {[25, 50, 75, 100].map((percentage) => (
              <button
                key={percentage}
                onClick={() => handlePercentageClick(percentage)}
                className="flex-1 py-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
              >
                {percentage}%
              </button>
            ))}
          </div>
        </div>

        {/* 总金额显示 */}
        <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
          <div className="flex justify-between text-sm">
            <span className="text-gray-600 dark:text-gray-400">总金额:</span>
            <span className="font-medium text-gray-900 dark:text-white">
              {totalAmount.toFixed(2)} {quoteCurrency}
            </span>
          </div>
        </div>

        {/* 可用余额 */}
        <div className="text-sm text-gray-500 dark:text-gray-400">
          可用: {activeTab === 'buy' ? 
            `${balances[quoteCurrency as keyof typeof balances].toLocaleString()} ${quoteCurrency}` :
            `${balances[baseCurrency as keyof typeof balances]} ${baseCurrency}`
          }
        </div>

        {/* 高级选项 */}
        <div>
          <button
            onClick={() => setIsAdvanced(!isAdvanced)}
            className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
          >
            {isAdvanced ? '隐藏' : '显示'}高级选项
          </button>
          
          {isAdvanced && (
            <div className="mt-3 space-y-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                  止损价格
                </label>
                <input
                  type="number"
                  value={stopLoss}
                  onChange={(e) => setStopLoss(e.target.value)}
                  className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                  placeholder="止损价格"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                  止盈价格
                </label>
                <input
                  type="number"
                  value={takeProfit}
                  onChange={(e) => setTakeProfit(e.target.value)}
                  className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                  placeholder="止盈价格"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
                  冰山委托可见数量
                </label>
                <input
                  type="number"
                  value={icebergVisible}
                  onChange={(e) => setIcebergVisible(e.target.value)}
                  className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                  placeholder="每次显示数量"
                />
              </div>
            </div>
          )}
        </div>

        {/* 提交按钮 */}
        <button
          onClick={handleSubmit}
          disabled={loading || !amount}
          className={`w-full py-3 rounded-md font-medium transition-colors ${
            activeTab === 'buy'
              ? 'bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white'
              : 'bg-red-600 hover:bg-red-700 disabled:bg-red-400 text-white'
          } disabled:opacity-50 disabled:cursor-not-allowed`}
        >
          {loading ? (
            <div className="flex items-center justify-center space-x-2">
              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
              <span>提交中...</span>
            </div>
          ) : (
            `${activeTab === 'buy' ? '买入' : '卖出'} ${baseCurrency}`
          )}
        </button>
      </div>
    </div>
  );
}
